package com.qf.ssm.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

@Component
public class MyChatHandler extends TextWebSocketHandler {

    private Map<Object, WebSocketSession> allClient=new HashMap<>();

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //我们保存的时候需要一个 key,这 key 从哪得到,用户在请求服务器的时候应该会传递一些唯一性的数据过来, 我们只要想办法获取到就行了
        System.err.println("用户和服务器建立 websocket 请求了");
        Object name = session.getAttributes().get("name");
        allClient.put(name, session);//以用户的唯一标识作为 key,将会话保存到了 map 中
        //获取离线的消息,发给对方
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.err.println("收到客户端发来的消息"+payload);
        //收到的消息应该转发给收消息的人
        Map map = objectMapper.readValue(payload, Map.class);//保存了数据的map
        //谁是收消息的人?
        Object toUser = map.get("toUser");
        //我们约定,发送的数据格式是 json,.其中有一个 key 叫 tuUser代表收消息的人, msg 代表消息内容
        //从保存的会话中获取收消息的人的会话
        WebSocketSession socketSession = allClient.get(toUser);
        //通过会话给对方发送数据
        if (socketSession != null&&socketSession.isOpen()) {
            Object from = session.getAttributes().get("name");
            socketSession.sendMessage(new TextMessage("收到了来自于"+from+"的消息,内容是:"+ map.get("msg")));
        }else{
            session.sendMessage(new TextMessage("对方不在线"));
            //可以保存消内容,等对方上线后发给对方
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
}
